import type { IApi } from 'umi';
import * as shell from 'shelljs';
import * as portfinder from 'portfinder'; 
import * as path from 'path';
import * as chalk from 'chalk';

export default async (api: IApi) => {
  api.describe({
    key: 'szworks',
    config: {
      default: true,
      schema(joi) {
        return joi.boolean();
      },
    },
  });

  const {NODE_ENV} = process.env;

  if(NODE_ENV === 'development') {
  
    api.onDevCompileDone(async ({ isFirstCompile, stats }) => {
      if(isFirstCompile){
        const port = await portfinder.getPortPromise({
          port: 9000,
        })
        shell.exec(`cross-env NODE_ENV=production && node ${path.resolve(__dirname, '../service/bootstrap.js')} PORT=${port} ENV=production`, {async: true})
        console.log(
        `
        ╔════════════════════════════════════════════════════╗
        ║  szworks listening at:                             ║
${chalk.cyan('ready')} - ║  > Local: ${chalk.cyan(`http://localhost:${port}`)}                    ║
        ║ Now you can open browser with the above addresses↑ ║
        ╚════════════════════════════════════════════════════╝
        `
        );
      }
    })

    // api.addEntryCode(async () => {
    //   console.log('------port--------- ', port);
    //   return `var newElem = document.createElement("img");
    //   newElem.src="http://localhost:"+${process.env.UMI_SZWORKS_PORT}+"/earth.png";
    //   newElem.onclick=() => {window.open("http://localhost:" + ${process.env.UMI_SZWORKS_PORT})}
    //   newElem.style.cssText="position:fixed;width:40px;height:40px;z-index:1000;right:10px;cursor: pointer;bottom: 10px;font-size: 30px"
    //   document.body.appendChild(newElem);`;
    // });
    
  }
}